﻿<%@ WebHandler Language="C#" Class="Ajax_usercontrol" %>

using System;
using System.Web;
using BackboneTest.BLL;
using BackboneTest.Models;
using Newtonsoft.Json;

public class Ajax_usercontrol : IHttpHandler {
    TB_UserBLL bll = new TB_UserBLL();
    TB_User model = new TB_User();
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");
        //int ID=
        if (!string.IsNullOrEmpty(context.Request.Params["ID"]))
        {
            model.ID = Convert.ToInt32(context.Request.Params["ID"].ToString());
        }
        
        //获取 http 传送方式
        string httpMethod = context.Request.HttpMethod;
        
        #region 读取内容
        string method = string.Empty;
        byte[] aa = new byte[context.Request.ContentLength];
        string ss = "";
        try
        {
            int r = context.Request.InputStream.Read(aa, 0, context.Request.ContentLength);
        }
        catch (Exception ex)
        {
            ss = ex.Message;
        }
        ss = System.Text.Encoding.UTF8.GetString(aa);
        if (!string.IsNullOrEmpty(ss))
        {
            model = JsonConvert.DeserializeObject<TB_User>(ss);
        }
        #endregion

        string msg = UserControl(model, httpMethod);
        if (string.IsNullOrEmpty(msg) || msg=="null")
        {
            context.Response.StatusCode = 500;
        }

        context.Response.Write(msg);
    }

    public string UserControl(TB_User model, string httpMethod)
    {
       
            string json = "";
            switch (httpMethod)
            {
                case "GET": 
                    break;
                case "POST":
                    json = JsonConvert.SerializeObject(bll.Register(model));
                    break;
                case "PUT":
                    json = JsonConvert.SerializeObject(bll.Update(model));
                    break;
                case "DELETE":
                   json = JsonConvert.SerializeObject(bll.Delete(model.ID));
                    
                    break;
            }

            return json;
          
    }
    
    public bool IsReusable {
        get {
            return false;
        }
    }

}